'''
Basic User Aministration

by Falko Krause
universal cake
by Christopher Steel
Voice of Access.org
'''

##################
from gluon.sqlhtml import form_factory
##################

@auth.requires(auth.has_membership(auth.id_group('uc_group_management')))
def index():

    response.flash = request.vars
    if request.vars.has_key('approve'):
        db(db.auth_user.id==request.vars['approve']).update(registration_key='')
        response.flash = 'Approved user %s'%db(db.auth_user.id==request.vars['approve']).select()[0].first_name
    elif request.vars.has_key('del_usergroup'):
        user_id = request.vars['del_usergroup']
        group_id = request.vars['del_groupuser']
        db((db.auth_membership.user_id==user_id) & (db.auth_membership.group_id==group_id)).delete()
    elif request.vars.has_key('delete'):
        pass
    elif request.vars.has_key('del_group'):
        db(db.auth_group.id == request.vars['del_group']).delete()
        response.flash = T('Group deleted')     
    elif request.vars.has_key('edit_group'):
        group = db(db.auth_group.id == request.vars['edit_group']).select()[0]
        #response.flash('Grupo apagado com sucesso')     
    elif request.vars.has_key('block_user'):
        import hashlib
        db(db.auth_user.id==request.vars['block_user']).update(
        registration_key="blocked")

    users = db(db.auth_user.id>0).select(orderby=db.auth_user.registration_key)
    forms_users_groups = {}
    for user in users:
        forms_users_groups[user.id] = form_factory(
                Field('group_id',label=T('Group ID'),requires = IS_IN_DB(db, 'auth_group.id', '%(role)s')),
                formname = 'fug%s'%user.id, submit_button=T('Submit')
                )
        if forms_users_groups[user.id].accepts(request.vars,formname='fug%s'%user.id):
            response.flash = T('Added user %s to group')%user.first_name
            if not db(db.auth_membership.user_id == user.id)(db.auth_membership.group_id == forms_users_groups[user.id].vars.group_id).count():
                db.auth_membership.insert(user_id=user.id ,group_id=forms_users_groups[user.id].vars.group_id )
                users = db(db.auth_user.id>0).select(orderby=db.auth_user.registration_key)

    if request.vars.has_key('edit_group'):
        form_group = SQLFORM(db.auth_group, record = group.id, formname='form_group', submit_button=T('Submit'))
    else:
        form_group = SQLFORM(db.auth_group, formname='form_group', submit_button=T('Submit'))
    if form_group.accepts(request.vars,formname = 'form_group'):
            response.flash = T('New Group Created')
    groups = db(db.auth_group.id>0).select()

    return dict(users=users, forms_users_groups = forms_users_groups, form_group = form_group, db_groups = groups)
